package com.ywu.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.logging.Logger;

/**
 * @ClassName TimerIdGenerateUtil
 * @Description TODO
 * @Author GroundDemo
 * @Date 2024/7/13 18:53
 * @Version 1.0
 **/
public class TimerIdGenerateUtil {
    private static final Logger log = Logger.getLogger(TimerIdGenerateUtil.class.getName());

    // id生成的长度
    private static final int idLength = 32;

    // 日期长度
    private static final int dataTimeLength = 17;

    // 毫秒级别生成的数量限制
    private static final int millisMaxNum = 999;

    // 毫秒级别生成的当前数量
    private static int millisCurrentNum = 0;

    // 存储当前生成的时间戳
    private static long currentTimeMillis;

    // 存储当前IP的后两段数据
    private static String ipNum = "";

    // 日期格式化字符串
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");

    static {
        // 初始化时读取当前服务的IP地址
        try {
            InetAddress localHost = Inet4Address.getLocalHost();
            String hostAddress = localHost.getHostAddress();
            String[] ips = hostAddress.split("\\.");
            // 读取后两位数据，固定三位，缺的以0补充
            ipNum = StringUtils.leftPad(ips[0], 3, "0") +
                    StringUtils.leftPad(ips[1], 3, "0") +
                    StringUtils.leftPad(ips[2], 3, "0") +
                    StringUtils.leftPad(ips[3], 3, "0");
        } catch (UnknownHostException e) {
            log.warning("TimerIdGenerateUtil get localHost ERROR !!");
            // 产生异常，采用补偿机制
            StringBuilder stringBuilder = new StringBuilder(12);
            Random random = new Random();
            for (int i = 0; i < 12; i++) {
                stringBuilder.append(random.nextInt(10));
            }
            ipNum = stringBuilder.toString();
        }

    }

    /**
    * @Author GroundDemo
    * @Description ID生成
    * @Date 19:23 2024/7/13
    * @Param []
    * @return java.lang.String
    **/
    public static String nextId() {
        long timeMillis = System.currentTimeMillis();
        // 锁住对象
        synchronized (TimerIdGenerateUtil.class) {
            if (millisCurrentNum >= millisMaxNum) {
                // 如果当时时间小于等于存储的当前时间，表明当前一毫秒之内生成的id数量已经超过了999的最大限制，需要下一毫米后执行
                if (timeMillis <= currentTimeMillis) {
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                // 重新将生成的上限置为0
                millisCurrentNum = 0;
            } else {
                millisCurrentNum++;
            }
            currentTimeMillis = timeMillis;
            // 格式化日期时间
            Date date = new Date(timeMillis);
            String formatDateStr = dateFormat.format(date);
            // 生成的ID格式为  日期+IP+millisCurrentNum
            return formatDateStr + ipNum + StringUtils.leftPad(String.valueOf(millisCurrentNum), 3, '0');
        }
    }
}
